<template>
  <div class="app-container">
    <div class="top-main">
    <el-form  class="top-form-fl" :model="param" label-width="auto" :inline="true">
      <el-form-item label="箱号">
        <MultipleBoxNumbersDialog v-model="param.containerNo" placeholder="请输入箱号" />
      </el-form-item>
      <el-form-item label="箱型">
        <el-select v-model="param.boxType" clearable style="width:100%" placeholder="选择箱型">
          <el-option v-for="item in param.boxTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="箱况">
        <el-select v-model="param.boxCondition" clearable style="width:100%" placeholder="选择箱况">
          <el-option v-for="item in param.boxCaseOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="提箱单号">
        <el-input v-model.trim="param.packingNo" clearable placeholder="请输入提箱单号"></el-input>
      </el-form-item>
      <el-form-item label="提箱日期">
        <el-date-picker v-model="param.packingDate" type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item label="客户">
        <el-input v-model.trim="param.buyBoxCompanyName" clearable placeholder="请输入客户"></el-input>
      </el-form-item>
    </el-form>
    <div class="top-from-fr">
        <el-button class="top-Search" @click="getTableData" type="primary">搜索</el-button>
        <el-button class="top-Refresh" @click="handleReset">重置</el-button>
      </div>   
    </div>

    <span style="float: right;">
      <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有集装箱" placement="left">
        <template v-if="isSelectAll">
          <el-button :icon="Finished" size="small" @click="slectAll" plain class="operatingArea">全选</el-button>
        </template>
        <template v-else>
            <el-button size="small" @click="deselectAll" plain class="operatingArea">取消全选</el-button>
        </template>
      </el-tooltip>
      <el-button type="primary" size="small" @click="toExportBuyBox" plain>导出</el-button>
    </span>

    <Table ref="tableRef" v-bind="table" :allId="allId" :isAllCheck="isAllCheck" style="width: 100%;"  @pageChange="onTablePageChange" @activDelete="activDelete"
      @showInfo="showInfo" @updateSelectAll="updateSelectAll" :disableHeaderCheckbox="disableHeaderCheckbox">
    </Table>

    <!--drawer -->
    <!-- info -->
    <el-dialog v-model="param.dialogVisibleInfo" :with-header="false" width="40%">
      <span class="_before">提箱记录详情</span>
      <!-- <el-row class="marginTop10">
        <el-col :span="8" class="text-right">客户：</el-col>
        <el-col :span="12">{{ param.boxInfo.buyBoxCompanyName }}</el-col>
      </el-row> -->
      <el-row class="marginTop10">
        <el-col :span="8" class="text-right">提箱单号：</el-col>
        <el-col :span="12">{{ param.boxInfo.packingNo }}</el-col>
      </el-row>
      <el-row class="marginTop10">
        <el-col :span="8" class="text-right">堆场名称：</el-col>
        <el-col :span="12">{{ param.boxInfo.yardName }}</el-col>
      </el-row>
      <el-row class="marginTop10">
        <el-col :span="8" class="text-right">箱号：</el-col>
        <el-col :span="12">{{ param.boxInfo.containerNo }}</el-col>
      </el-row>
      <el-row class="marginTop10">
        <el-col :span="8" class="text-right">箱型/箱况</el-col>
        <el-col :span="24"></el-col>
        <el-col :offset="6" :span="12">
          <el-table :data="param.boxInfo.tableBox" style="width: 100%" align="center">
            <el-table-column prop="boxType" label="箱型" width="180"  align="center"> </el-table-column>
            <!-- <el-table-column prop="totalQuantity" label="箱量" width="180"> </el-table-column> -->
            <el-table-column prop="boxCondition" label="箱况"  align="center"> </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row class="marginTop10">
        <el-col :span="8" class="text-right">提箱日期：</el-col>
        <el-col :span="12">{{ formatDate(param.boxInfo.packingDate, 2) }}</el-col>
      </el-row>
      
      <el-row class="marginTop10">
        <el-col :span="8" class="text-right">提箱单附件：</el-col>
        <el-col :span="12"> 
          <showFile :detailFileList="param.boxInfo.detailFileList"></showFile>
        </el-col>
      </el-row>
    </el-dialog>

    <!-- warning-->
    <el-dialog v-model="param.dialogVisible" title="系统提示" width="500">
      <span>确认删除该用户？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="param.dialogVisible = false">取消</el-button>
          <el-button @click="param.dialogVisible = false">是的</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import Table from '@/components/table'
import showFile from '@/components/upload/showFile.vue'
// import czTages from '@/components/chengzhiTags'  
import { saleBoxPage, batchFinish, getPackingInfo } from '@/api/boxDeal/tiXiangManage';
import { addPackingDetail, saleBoxPage as getDetailTable, getPackingDetail,exportSaleBoxPackingListDetail } from '@/api/boxDeal/tiXiangManageDetail';
import { computed, onMounted, onActivated, reactive, ref } from 'vue';
import {Plus,Delete,Edit,Message,Search,Download,Upload,Refresh,UploadFilled} from '@element-plus/icons-vue'
import { ElMessage,ElMessageBox } from 'element-plus';
import { formatDate } from '@/utils'
import { downloadFile } from '@/utils/download'
import MultipleBoxNumbersDialog from '@/components/dialog/multipleBoxNumbersDialog.vue'
import {formatContainerNo} from '@/utils/mlpBox' // 格式化箱号
import {useRoute} from 'vue-router'

const param = reactive({
  containerNo:'',
  value1: [],
  boxInfo: { code: '123456789', type: "40HQ", info: "无" },
  pageNum: 0,
  pageSize: 10,
  dialogTableVisible: false,
  drawer: false,
  dialogEditVisible: false,
  dialogVisible: false,
  dialogPathVisible: false,
  statusFilter: { 5: '已发放', 10: '已下载', 15: '提箱中', 20: '已完成', 25: '作废', 30: '已过期' },

  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: '5', label: '40HQ', },
    { value: '10', label: '40GP', },
    { value: '15', label: '20HQ', },
    { value: '20', label: '20GP', },
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    { value: '5', label: '全新', },
    // { value: '20', label: '混提(次新或者适货)', },
  ],
});
const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    { key: 'containerNo', colWidth: '100', title: '箱号', type: '<a>', command: 'showInfo', isCheck: true },
    { key: 'boxType', colWidth: '60', title: '箱型', type: 'filter', filter: { 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' }, isCheck: true },
    { key: 'boxCondition', title: '箱况', type: 'filter', filter: { 5: '全新', 10: '次新', 15: '适货' }, isCheck: true },
    { key: 'packingDate', title: '提箱日期', type: 'date', isCheck: true },
    // { key: 'buyBoxCompanyName', title: '客户', type: 'text', isCheck: true },
    { key: 'packingNo', title: '提箱单号', type: '<a>', isCheck: true },
    { key: 'yardName', title: '堆场名称', type: 'text', isCheck: true },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  },
});
const route = useRoute();

onActivated(() => {
   if(route.query.refNo){
    param.containerNo=route.query.refNo
  }
  getTableData()
})

/*# 过滤条件：提箱单Id:packingId 提箱单号:packingNo  集装箱箱型：boxType 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP 
# 集装箱箱况：boxCondition 5-全新   10-次新  15-适货  集装箱箱号:containerNo
# 提箱日期时间区间:  beginPackingDate  endPackingDate
# 买箱公司Id:buyBoxCompanyId  买箱公司名称:buyBoxCompanyName
*/
const getTableData = () => {
  const { container, containerList } = formatContainerNo(param.containerNo);
  let data = {
    containerNo: container, // 单箱号查询
    containerNos: containerList, // 多箱号查询
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    packingNo: param.packingNo,
    boxType: param.boxType,
    boxCondition: param.boxCondition,
    buyBoxCompanyName: param.buyBoxCompanyName
  }
  if (param.packingDate) {
    console.log(param.packingDate)
    data.beginPackingDate = param.packingDate[0]
    data.endPackingDate = param.packingDate[1]
  }
  getDetailTable(data).then((res: any) => {
    table.data = res.data.list;
    table.config.total = res.data.total;
  })
}
function handleReset() {
  param.containerNo = null
  param.packingNo = null
  param.boxType = null
  param.boxCondition = null
  param.buyBoxCompanyName = null
  param.packingDate = null
  getTableData()
}

//删除  
const activDelete = (row: any) => {
  // data.value.activityId = row.activityId;
  // data.value.handleOperate = 'edit';
  param.dialogVisible = true;
};
const tableRef = ref({multipleSelection:[]});

//详情
const showInfo = (row: any) => {
  if (!row.id) {
    ElMessage.error('提箱单 id 为空')
  }
  // getPackingInfo(row.id).then((res: any) => {
  getPackingDetail(row.id).then((res: any) => {
    let resp = res.data
    param.boxInfo = resp
    param.boxInfo.containerNo = row.containerNo
    param.boxInfo.detailFileList = resp.detailFileList || []
    param.boxInfo.tableBox = [{
      boxType: boxTypeFilter(resp.boxType),
      totalQuantity: resp.totalQuantity,
      boxCondition: boxConditionFilter(resp.boxCondition),
    }]
  })
  param.dialogVisibleInfo = true;
};

//分页
function onTablePageChange(page: any) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};

//过滤
const boxTypeFilter = (val: any) => {
  let result = ''
  const boxConditionList = [{ value: 5, label: '40HQ' }, { value: 10, label: '40GP' }, { value: 15, label: '20HQ' }, { value: 20, label: '20GP' }]
  boxConditionList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
const boxConditionFilter = (val: any) => {
  let result = ''
  const boxTypeList = [{ value: 15, label: '适货' }, { value: 10, label: '次新' }, { value: 20, label: '混提' },{ value: 5, label: '全新' }]
  boxTypeList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}

const toExportBuyBox = () => { 
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }
  const ids = checkAllItem.map((item: any) => item.id)

    if (ids.length < 1) return ElMessage.warning('请选择需要导出的箱号！')
    ElMessageBox.confirm('确认要导出选中的箱号？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        let reqParameters = {
          purchaseIds: ids
        }
        exportSaleBoxPackingListDetail(reqParameters).then((res: any) => {
            downloadFile(res, '提箱记录')
          
        }).catch((error) => {
            ElMessage.error(error)
        })
    }).catch(() => {
        // ElMessage.warning('请选择要收取的箱号！')
    })
}



const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const allId = ref([]) // 使用全选功能时使用
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）

const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const slectAll = async(val:any) =>{
    checkAll.value = []
    await getDetailTable({ pageNum:1,pageSize:10000}).then(res =>{ 
      if(res.code == "00000" && res.data.list && res.data.total){
        isSelectAll.value = false
        disableHeaderCheckbox.value = true
        res.data.list.forEach(item => {
          checkAll.value.push(item)
        })
        isAllCheck.value = true
        allId.value = checkAll.value
        tableRef.value.checkAll()
      }else{
        ElMessage.error("全选失败，请刷新页面，或者手动选择")
      }
 })
}
const deselectAll = () =>{
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef.value.clearCheckAll()
  isSelectAll.value = true
}

const updateSelectAll = (val) => {
  allId.value = val
  // console.log("11111",allId.value)
}
</script>

<style lang="scss" scoped>
.el-form-diy {
  padding: 10px;

  div {
    width: 100%;
  }
}
</style>
